<template>
  <h3 style="display: flex">节拍分析模块:</h3>
  <div>
    <div ref="chart" style="width: 1300px; height: 500px; padding-right: 50px"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import axios from "axios";
import { markRaw } from "vue";

export default {
  name: "",
  data() {
    return {
      chart: null,
      mockdata: [],
      targetCycleData: [],
      targetCycleDataMapped: [],
      stationsToExclude: [
        "1210S1",
        "2080M",
        "3020M",
        "2170M",
        "1355B",
        "2410M",
        "2140M",
        "1350A-2",
        "2090M",
        "3030S1",
        "1210S2",
        "3120M",
        "2370M",
        "1420M",
        "2440M",
        "1006R",
        "1008B",
        "1035B",
        "1040M",
        "1095B",
        "1096R",
        "1115B",
        "1126R",
        "1150M",
        "1165B",
        "1195B",
        "1196R",
        "1445R",
        "1235B",
        "1245B",
        "1265R",
        "1070M",
        "1075B",
        "1266R",
        "1270M",
        "1315B",
        "1366R",
        "1368B",
        "1090A",
        "1416R",
        "1430M-2",
        "2040M",
        "2055B",
        "2115B",
        "2145R",
        "2006R",
        "2356R",
        "3105R",
        "2120M",
        "2135B",
        "2155B",
        "2196R",
        "2225R",
        "1405B",
        "2236R",
        "2370A",
        "2420M",
        "2430M",
        "2450M",
        "2476R",
        "2505B",
        "1140M",
        "1160A",
        "2185B",
        "2475A",
        "2320M",
        "3110A",
        "3040S",
        "3030S2",
        "2255M",
      ],
    };
  },
  async mounted() {
    try {
      await this.fetchDataFromApi();
      console.log("接口返回的完整数据:", this.mockdata);
      console.log("目标节拍数据:", this.targetCycleData);
      this.initChart();
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  },
  methods: {
    async fetchDataFromApi() {
      try {
        const response = await axios.get("http://10.64.35.32:8000/as_manage_analysis/get_fine_as_data/?page=1&page_size=150");
        this.mockdata = response.data.results;
        const response1 = await axios.get("http://10.64.35.32:8000/as_manage_analysis/get_as_cycle_data/?page=1&page_size=1");
        this.targetCycleData = response1.data.results[0].cycle;
        this.targetCycleDataMapped = Object.entries(this.targetCycleData).map(([station, cycle]) => ({
          name: station,
          value: [station, cycle],
        }));

        this.mockdata.forEach((station) => {
          const targetCycle = this.targetCycleData[station.station];
          if (targetCycle !== undefined) {
            station.targetCycle = targetCycle;
          }
        });

        this.initChart();
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    },
    initChart() {
      this.chart = markRaw(echarts.init(this.$refs.chart));

      const targetCycleForStations = this.mockdata.reduce((acc, station) => {
        const targetCycle = this.targetCycleData[station.station];
        if (targetCycle !== undefined) {
          acc.push({ name: station.station, value: targetCycle });
        }
        return acc;
      }, []);

      const option = {
        title: {
          text: "",
          left: "center",
          top: 20,
          textStyle: {
            fontSize: 20,
            fontWeight: "bold",
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: function (params) {
            const dataIndex = params[0].dataIndex;

            const detailData = filteredData[dataIndex];

            const targetCycle = detailData.targetCycle;

            const totalProduced = detailData.count_good + detailData.count_reject;

            // 避免除零错误
            if (totalProduced === 0) {
              return `<strong>${detailData.station}</strong><br>无法计算`;
            }

            const overcycle_ratio = (detailData.overcycle / totalProduced) * 100;

            let tooltipContent = `<strong>${detailData.station}</strong><br>`;
            tooltipContent += `平均节拍: ${detailData.cycletime}s<br>`;
            tooltipContent += `目标节拍: ${targetCycle}s<br>`;
            tooltipContent += `FTQ: ${(detailData.ftq * 100).toFixed(2)}%<br>`;
            tooltipContent += `合格数: ${detailData.count_good}<br>`;
            tooltipContent += `不合格数: ${detailData.count_reject}<br>`;
            tooltipContent += `最大节拍: ${detailData.maxcycle}s<br>`;
            tooltipContent += `最小节拍: ${detailData.mincycle}s<br>`;
            tooltipContent += `超节拍数量: ${detailData.overcycle}<br>`;
            tooltipContent += `超节拍比例: ${overcycle_ratio.toFixed(2)}%`;

            return tooltipContent;
          }.bind(this),
        },
        legend: {
          data: ["平均节拍", "FTQ", "超节拍比例", "目标节拍"],
        },
        xAxis: {
          type: "category",
          data: this.mockdata.map((item) => item.station),
        },

        dataZoom: [
          {
            type: "slider",
            show: true,
            start: 0,
            end: 100,
            handleSize: "80%",
            height: 20,
          },
          {
            type: "inside",
            show: true,
            start: 0,
            end: 100,
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "节拍",
            position: "left",
            axisLabel: {
              formatter: "{value}",
            },
          },
          {
            type: "value",
            name: "Rate (%)",
            position: "right",
            axisLabel: {
              formatter: "{value} %",
            },
            max: 100,
          },
        ],
        series: [
          {
            name: "平均节拍",
            type: "bar",
            data: this.mockdata.map((item) => item.cycletime),
            yAxisIndex: 0,
          },
          {
            name: "FTQ",
            type: "line",
            data: this.mockdata.map((item) => parseFloat(item.ftq) * 100),
            yAxisIndex: 1,
            label: {
              show: true,
              formatter: function (params) {
                return params.value.toFixed(2) + " %";
              },
            },
          },
          {
            name: "超节拍比例",
            type: "line",
            data: this.mockdata.map((item) => (item.overcycle / (item.count_good + item.count_reject)) * 100),
            yAxisIndex: 1,
            label: {
              show: true,
              formatter: function (params) {
                return params.value.toFixed(2) + " %";
              },
            },
          },
        ],
      };
      // 过滤数据
      const filteredData = this.mockdata.filter((item) => !this.stationsToExclude.includes(item.station));
      const targetCycleFiltered = Object.entries(this.targetCycleData)
        .filter(([station]) => !this.stationsToExclude.includes(station))
        .reduce((acc, [station, cycle]) => ({ ...acc, [station]: cycle }), {});

      this.targetCycleData = targetCycleFiltered;
      option.xAxis.data = filteredData.map((item) => item.station);
      const validTargetCycles = targetCycleForStations.filter(({ value }) => value !== null && value !== "N/A");

      option.series.push({
        name: "目标节拍",
        type: "line",
        step: "start",
        data: validTargetCycles.map((item) => item.value),
        symbol: "circle",
        lineStyle: {
          color: "orange",
          width: 1.4,
          type: "dashed",
        },
        yAxisIndex: 0,
      });

      option.series.forEach((series, index) => {
        switch (index) {
          case 0:
            series.data = filteredData.map((item) => item.cycletime);
            break;
          case 1:
            series.data = filteredData.map((item) => parseFloat(item.ftq) * 100);
            break;
          case 2:
            series.data = filteredData.map((item) => (item.overcycle / item.count_good) * 100);
            break;
        }
      });
      this.chart.setOption(option);
    },
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
  },
};
</script>

<style scoped>
h3 {
  color: rgb(0, 0, 0);
}

.block {
  padding: 20px;
  text-align: center;
  /* border-right: solid 1px var(--el-border-color); */
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>
